const axios = require('./request')
const cheer = require('cheerio')
const log4js = require('../../config/log4js')
const log = log4js.getLogger('schedule')

async function getSearchList (skey) {
  return axios.post('http://cn.epubee.com/keys/get_ebook_list_search.asmx/getSearchList',
    { skey }
  )
}

async function onlineAddBook (bookid, uid) {
  return axios.post('http://cn.epubee.com/app_books/addbook.asmx/online_addbook',
    `{bookid:'${bookid}',uid:${uid},act:'searchmm'}`, {
      headers: {
        Accept: 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        Host: 'cn.epubee.com',
        Origin: 'http://cn.epubee.com',
        Referer: 'http://cn.epubee.com/books/?s=%E5%9B%B4%E5%9F%8E',
        'Cache-Control': 'no-cache',
        Pragma: 'no-cache',
        Connection: 'keep-alive'
      }
    })
}

/**
 * 登录epubee平台
 * @param {string} uid
 * @param {string} email
 * @param {string} password
 * @returns {string} 下次访问时需携带的Cookie
 */
async function login (uid, email, password) {
  // return 'ASP.NET_SessionId=miooiir5z2ucx05q5gbgtqsz; identify=3975418; expires=Mon, 13-Nov-2017 05:34:18 GMT; eidentify=157571C6AA2D753FFBD06A02894FC065; user_localid=ip_115.206.57.145; expires=Mon, 13-Nov-2017 05:34:18 GMT; isVip=0; expires=Mon, 13-Nov-2017 05:34:18 GMT; messagescount=0; expires=Mon, 13-Nov-2017 05:34:18 GMT; demandcount=0; expires=Mon, 13-Nov-2017 05:34:18 GMT; identifyusername=; expires=Mon, 13-Nov-2017 05:34:18 GMT; kindle_email=; expires=Mon, 13-Nov-2017 05:34:18 GMT; uemail=; expires=Mon, 13-Nov-2017 05:34:18 GMT; '
  const res = await axios.get('http://cn.epubee.com/files.aspx')
  let cookies = ''
  res.headers['set-cookie'].forEach(item => {
    const c = item.substring(0, item.lastIndexOf('; path'))
    cookies = cookies + c + '; '
  })
  const res2 = await axios.post('http://cn.epubee.com/keys/retrieve_cloud_id.asmx/Retrieve', {
    eID: email,
    userpassword: password
  }, {
    headers: {
      Cookie: cookies
    }
  })
  log.info(res2.data.d[0])
  const eidentify = res2.data.d[0]['eID']
  return cookies
    .replace('identify=0;', `identify=${uid};`)
    .replace('eidentify=;', `eidentify=${eidentify};`)
    .replace('isVip=0', 'isVip=1')
}

async function getEBookList (uid) {
  return axios.get('http://cn.epubee.com/files.aspx', {
    transformResponse: [
      (data) => {
        const $ = cheer.load(data)
        const contents = $('.listEbook .contentshow')
        const list = []
        for (let i = 0; i < contents.length; i++) {
          const bname = $(`#gvBooks_lblTitle_${i}`).text()
          const author = $(`#gvBooks_lblAuthor_${i}`).text()
          const bid = $(`#gvBooks_gvBooks_child_${i}_hpdownload_0`).attr('target')
          list.push({
            bname,
            author,
            bid
          })
        }
        return list
      }
    ],
    headers: {
      Cookie: `identify=${uid};`
    }
  })
}

async function getTempBid (uid, bname, author) {
  const res = await getEBookList(uid)
  const books = res.data
  const maybeResults = []
  for (let i = 0; i < books.length; i++) { // 先只比较书名
    if (bname === books[i].bname) {
      maybeResults.push(books[i])
    }
  }
  if (maybeResults.length === 0) {
    log.info(res)
    throw new Error('未找到相应书籍')
  }
  if (maybeResults.length === 1) {
    return maybeResults[0].bid
  }
  for (let i = 0; i < maybeResults.length; i++) { // 有重复的书名 然后比较作者名
    if (author === maybeResults[i].author) {
      return maybeResults[i].bid
    }
  }
  return maybeResults[0].bid // 作者名没有匹配的？这可以视为epubee的Bug了，那就返回书名第一个匹配的书Id
}

async function getKey (uid, bid) {
  return axios.post('http://cn.epubee.com/app_books/click_key.asmx/getkey', {
    isVip: 1,
    uid,
    strbid: bid
  })
}

async function download (bid, uid, key) {
  return axios.get(`http://files.epubee.com/getFile.ashx?bid=${bid}&uid=${uid}&t_key=${key}`, {
    responseType: 'arraybuffer',
    timeout: 1000 * 60 * 30
  })
}

/**
 * 删除保存到epubee书架中的书籍
 * @param {string} uid
 * @param {string} bids 最前面一个0, 其余以英文逗号分隔
 */
async function deleteMyBooks (uid, bids) {
  return axios.post('http://cn.epubee.com/app_books/deletemybooks.asmx/deletemybooks', {
    uid,
    bids
    // bids:'0,qiEzfHwXgRIxmxaRo6At%2b1x%2bJXRFh0CXUIE3T3JgcMJ3DeKd7eJ3MfNibVmJHSG6f5sOeod8GVV4b3D2RAqsPy2WNu0b2vZxLWbrWUIc1ZbIPFzGUlGA7h2uQvMJ4BR3AZz0joNjlvQ%3d,JzOavJf0v%2btEBNidu7ZVLf%2fQ4DowCrLYADSXiFLGmWegFZjXd6KuFeLhNXsQjnQ%2bPgNHsvWgA6MJFifXAs8TOCNlBm6CQ7%2bLH9ZG8ihElJuR3yd2q73MfV%2bU%2bKMl1oVoF3peqJwKseI%3d'
  })
}

// getEBookList('42066828').then((res) => {
//   console.log(res.data)
// })

module.exports = {
  getSearchList,
  onlineAddBook,
  login,
  getTempBid,
  getKey,
  download,
  deleteMyBooks
}
